package com.example.systemwork.entity;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

@Entity
@Getter
@Setter
@DiscriminatorValue("1")
public class Customer extends User {
    @Column
    private String customerName;

    @OneToMany(mappedBy = "customer",
            fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    @JsonIgnoreProperties(value = {"customer"})
    private Set<Torder> torders;

    public Torder createOrder(Shop shop){
        Torder torder = findUnpayOrder(shop);
        if(torder==null){
            torder=new Torder();
            torder.setShop(shop);
            torder.setStatus(0);
            torder.setCustomer(this);
            torders.add(torder);
        }
        return torder;
    }

    private Torder findUnpayOrder(Shop shop){
        AtomicReference<Torder> result= new AtomicReference<>(null);
        torders.forEach(torder ->{
            if(torder.getStatus().equals(0)&&torder.getShop().equals(shop)){
                result.set(torder);
            }
        });
        return result.get();
    }


}
